#include "customdialog.h"
#include "ui_customdialog.h"
#include <QFile>
#include <QMessageBox>
#include <QDir>

CustomDialog::CustomDialog(QWidget *parent) :
    QDialog(parent),
    m_ui(new Ui::CustomDialog)
{
    m_ui->setupUi(this);
	m_ui->textEdit->setFocus();
	QString strHome = QDir::homePath ();
	QFile file(strHome + "/.radioget/custom.conf");
	if(file.open(QIODevice::ReadOnly|QIODevice::Text))
	{
		QString str=file.readAll();
		file.close();
		m_ui->textEdit->append(str);
	}
	else{
		QString str=";一行一条，半角分号开头表示注释，格式：\n"
					";电台名称=电台链接，注意等号用半角，示例：\n"
					"江西新闻综合=mms://movie.jxgdw.com/jswjxdt\n"
					"江西音乐广播=mms://tv.jxgdw.com/jswwyyy\n"
					"江西农村广播=mms://tv.jxgdw.com/jswkjnc\n"
					"\n"
					"\n";
		m_ui->textEdit->append(str);
	}
}

CustomDialog::~CustomDialog()
{
    delete m_ui;
}

void CustomDialog::changeEvent(QEvent *e)
{
    switch (e->type()) {
    case QEvent::LanguageChange:
        m_ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void CustomDialog::on_buttonBox_accepted()
{
	QStringList strlist = m_ui->textEdit->toPlainText().split("\n");
	bool accept = true;
	int line = 0;
	for (int i=0; i < strlist.size(); i++)
	{
		line++;
		QString eachline = strlist.at(i);
		if (eachline.startsWith(";") || eachline.startsWith("#")
				|| eachline.size() == 0)
			continue;
		QStringList tmp = eachline.split("=");
		if (tmp.size() != 2)
		{
			accept = false;
			break;
		}
		if (!tmp.at(1).startsWith("mms://") && !tmp.at(1).startsWith("rtsp://"))
		{
			accept = false;
			break;
		}
	}
	if (!accept)
	{
		QString num;
		num.setNum(line);
		QMessageBox::information(this, "错误", "第" + num + "行有错误，请重新填写！");
		return;
	}

	QString strHome = QDir::homePath ();
	QFile file(strHome + "/.radioget/custom.conf");
	bool bRet = file.open(QIODevice::Text|QIODevice::WriteOnly|QIODevice::Truncate);
	if(!bRet){
		QMessageBox::critical(0,"错误","无法写入文件！");
		return;
	}
	file.write(m_ui->textEdit->toPlainText().toUtf8());
	file.close();
	this->close();
}

void CustomDialog::on_buttonBox_rejected()
{

}

